"""
会话管理模块
"""

import secrets
import time
from typing import Dict, Optional

class SessionManager:
    """会话管理器"""
    
    def __init__(self):
        """初始化会话管理器"""
        self.sessions: Dict[str, Dict] = {}
        self.session_timeout = 3600  # 1小时超时
    
    def create_session(self, user_id: int) -> str:
        """创建会话"""
        session_id = secrets.token_urlsafe(32)
        current_time = time.time()
        
        self.sessions[session_id] = {
            'user_id': user_id,
            'created_at': current_time,
            'last_accessed': current_time
        }
        
        return session_id
    
    def validate_session(self, session_id: str) -> bool:
        """验证会话是否有效"""
        if session_id not in self.sessions:
            return False
        
        session = self.sessions[session_id]
        current_time = time.time()
        
        # 检查是否超时
        if current_time - session['last_accessed'] > self.session_timeout:
            del self.sessions[session_id]
            return False
        
        # 更新最后访问时间
        session['last_accessed'] = current_time
        return True
    
    def destroy_session(self, session_id: str) -> bool:
        """销毁会话"""
        if session_id in self.sessions:
            del self.sessions[session_id]
            return True
        return False
    
    def get_user_id(self, session_id: str) -> Optional[int]:
        """根据会话ID获取用户ID"""
        if self.validate_session(session_id):
            return self.sessions[session_id]['user_id']
        return None
    
    def cleanup_expired_sessions(self):
        """清理过期会话"""
        current_time = time.time()
        expired_sessions = []
        
        for session_id, session in self.sessions.items():
            if current_time - session['last_accessed'] > self.session_timeout:
                expired_sessions.append(session_id)
        
        for session_id in expired_sessions:
            del self.sessions[session_id]
    
    def get_session_count(self) -> int:
        """获取当前会话数量"""
        return len(self.sessions)
    
    def get_session_info(self, session_id: str) -> Optional[Dict]:
        """获取会话信息"""
        if session_id in self.sessions:
            return self.sessions[session_id].copy()
        return None
